<template>
    <div class="order-sum" v-loading="loading">
        <div class="tabs-wrap clearfloat">
            <el-tabs v-model="activeTabs" @tab-click="tabChange" class="tabs fl">
                <el-tab-pane label="奖励审核" name="reward"></el-tab-pane>
                <el-tab-pane label="惩戒审核" name="publish"></el-tab-pane>
            </el-tabs>
            <div class="fr" style="margin-top: -60px;position: relative; z-index: 99">
                <el-button @click="add">+添加{{this.activeTabs == 'reward' ? '奖励' : '惩戒'}}</el-button>
            </div>
            <div class="fr" style="margin-top: -60px;margin-right: 100px">
                <span class="down-execel">
                    <Poptip v-model="showFilter" placement="bottom-end">
                        <i class="el-icon-search poptip-condition-add"></i>
                        <a href="javascript:;" class='poptip-condition-add'>列表查找</a>
                        <div slot="content">
                            <Poptip v-model="showFilterCondition" placement="bottom-start" class='poptip-condition'>
                                <i class="el-icon-plus"></i>
                                <a href="javascript:;">添加过滤条件</a>
                                <div slot="content" class="condition-list">
                                    <ul>
                                        <li
                                            v-for="(item, index) in selectHead"
                                            :key="index"
                                            class='poptip-condition-item'
                                            @click="addFilterCondition(item)">
                                            {{item.label}}
                                        </li>
                                    </ul>
                                </div>
                            </Poptip>
                            <el-form :model="conditionForm" @submit.native.prevent ref="conditionForm" label-width="120px" class="demo-dynamic">
                                <el-form-item
                                    v-for="(condition, index) in conditionForm.condition"
                                    :label="condition.label"
                                    :key="condition.key"
                                    :prop="'condition.' + index + '.value'"
                                    :rules="{required: true, message: condition.label + '不能为空', trigger: 'blur'}">
                                    <el-select
                                        v-if='condition.label === "流程人员"'
                                        v-model="condition.value"
                                        placeholder="请选择流程人员"
                                        size="small"
                                        filterable
                                    >
                                        <el-option
                                            v-for="item in processOptions"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        ></el-option>
                                    </el-select>
                                    <el-select
                                        v-else-if='condition.label === "代理人"'
                                        v-model="condition.value"
                                        placeholder="请选择代理人"
                                        size="small"
                                        filterable
                                    >
                                        <el-option
                                            v-for="item in agentOptions"
                                            :key="item.id"
                                            :label="item | agentNumAddName"
                                            :value="item.id"
                                        ></el-option>
                                    </el-select>
                                    <el-select
                                        v-else-if='condition.label === "申请人"'
                                        v-model="condition.value"
                                        placeholder="请选择申请人"
                                        size="small"
                                        filterable
                                    >
                                        <el-option
                                            v-for="item in adminOptions"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        ></el-option>
                                    </el-select>
                                    <el-select
                                        v-else-if='condition.label === "类型"'
                                        v-model="condition.value"
                                        placeholder="请选择类型"
                                        size="small"
                                        filterable
                                    >
                                        <el-option
                                            :label="activeTabs == 'reward' ? '结算奖励' : '结算惩戒'"
                                            :value="1">
                                        </el-option>
                                        <el-option
                                            :label="activeTabs == 'reward' ? '代理人奖励' : '代理人惩戒'"
                                            :value="2">
                                        </el-option>
                                    </el-select>
                                    <el-date-picker
                                        v-model="condition.value"
                                        type="daterange"
                                        placeholder="选择日期"
                                        value-format="yyyy-MM-dd"
                                        size="small"
                                        :validate-event='false'
                                        v-else-if='condition.label === "时间选择"'>
                                    </el-date-picker>
                                    <el-input v-else size="small" v-model="condition.value" @keyup.enter.native="submitsearch('conditionForm')"></el-input>
                                    <el-button @click.stop="removeDomain(condition)" size="mini">删除</el-button>
                                </el-form-item>
                            </el-form>

                            <div class="btns">
                                <el-button @click="submitsearch('conditionForm')" size="mini">查询</el-button>
                                <el-button @click="resetForm('conditionForm')" size="mini">重置</el-button>
                            </div>
                        </div>
                    </Poptip>
                </span>
            </div>
        </div>

        <el-table
            :data="tableData"
            ref="order-table"
            border
            v-if="table_show"
            @sort-change='tableSortChange'
        >
            <el-table-column
                width="60"
                align="center"
                label="ID"
            >
                <template slot-scope="scope">
                    {{(scope.$index + 1) + (current_page - 1) * per_page}}
                </template>
            </el-table-column>
            <el-table-column
                label="代理人"
                sortable="custom"
                prop="agent_id"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    {{scope.row.agent ? scope.row.agent.name : '-'}}
                </template>
            </el-table-column>
            <el-table-column
                label="类型"
                sortable="custom"
                prop="type"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span v-if="activeTabs == 'reward'">
                        {{scope.row.type == 1 ? '结算奖励' : '代理人奖励'}}
                    </span>
                    <span v-else>
                        {{scope.row.type == 1 ? '结算惩戒' : '代理人惩戒'}}
                    </span>
                </template>
            </el-table-column>
            <el-table-column
                :label="activeTabs == 'reward' ? '奖励金额(元)' : '惩戒金额(元)'"
                :prop="activeTabs == 'reward' ? 'reward' : 'deduction_price'"
                sortable="custom"
                align="center"
                :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column
                :label="activeTabs == 'reward' ? '奖励原因' : '惩戒原因'"
                sortable="custom"
                :prop="activeTabs == 'reward' ? 'reason' : 'name'"
                :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column
                label="申请人"
                prop="applicant_id"
                sortable="custom"
                align="center"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    {{scope.row.applicant ? scope.row.applicant.name : '-'}}
                </template>
            </el-table-column>
            <el-table-column
                label="申请时间"
                prop="created_at"
                sortable="custom"
                align="center"
                :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                v-if="$store.state.user.role_id == 1"
            >
                <template slot-scope="scope">
                    <el-button size="small" type="primary" @click="operate('yes', scope.row)">通过</el-button>
                    <el-button size="small" type="danger" @click="operate('no', scope.row)">拒绝</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination @paginationChange="pageChange" :total="total" v-if="table_show"></pagination>
        <add-active ref="add-active" :agentOptions="agentOptions" @refresh="getTableData"></add-active>
    </div>
</template>

<script>
import pagination from '~/components/pagination'
import addActive from './components/add-active'
export default {
    components: {
        pagination,
        addActive
    },

    data() {
        return {
            table_show: true,
            loading: false,
            activeTabs: 'reward',
            tableData: [],
            current_page: 1,
            agentOptions: [],
            adminOptions: [],
            per_page: 25,
            total: 0,
            sort_params: {},
            search_params: {},
            showFilter: false,
            showFilterCondition: false,
            // 筛选条件
            conditionForm: {
                condition: []
            },
            selectHead: [
                {
                    label: '类型',
                    props: 'type'
                },
                {
                    label: '代理人',
                    props: 'agent_id'
                },
                {
                    label: '申请人',
                    props: 'applicant_id'
                },
                {
                    label: '时间选择',
                    props: 'time'
                }
            ],
        }
    },

    created() {
        this.getAllAgent()
        this.getTableData()
    },

    methods: {
        add() {
            this.$refs['add-active'].showOn(this.activeTabs)
        },
        tabChange(val) {
            this.search_params = {}
            this.sort_params = {}
            this.current_page = 1
            this.per_page = 25
            this.conditionForm.condition = []
            this.table_show = false
            this.$nextTick(() => {
                this.table_show = true
            })
            this.getTableData()
        },
        operate(pass, data) {
            let params = {
                pass: pass
            }
            let msg = pass == 'yes' ? '确定通过奖励审核吗？' : '确定拒绝奖励审核吗？'
            if (this.activeTabs != 'reward') {
                msg = pass == 'yes' ? '确定通过惩戒审核吗？' : '确定拒绝惩戒审核吗？'
            }
            this.$confirm(msg, '提醒', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                center: true,
            }).then(() => {
                this.rewardPost(params, data)
            }).catch(() => {})
        },
        rewardPost(params, data) {
            let url = this.activeTabs == 'reward' ? `/api/rewardRecord/${data.id}` : `/api/deduction/${data.id}`
            if (data.type == 2) {
                url = this.activeTabs == 'reward' ? `/api/rewardRecord/${data.id}/agent_reward_record_auditor` : `/api/deduction/${data.id}/agent_deduction_auditor`
            }
            this.$axios.put(url, params).then(res => {
                if (res.data.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '操作成功'
                    })
                    this.getTableData()
                } else {
                    this.$message({
                        type: 'error',
                        message: res.data.message
                    })
                }
            }).catch(e => {
                console.log(e)
            })
        },
        tableSortChange(column) {
            this.sort_params = {
                sort_str: column.prop
            }
            if (column.order == 'ascending') {
                this.sort_params.sort_order = 'asc'
            } else if (column.order == 'descending') {
                this.sort_params.sort_order = 'desc'
            } else {
                this.sort_params = {}
            }
            this.getTableData()
        },
        pageChange(data) {
            this.per_page = data.perPage
            this.current_page = data.page
            this.getTableData()
        },
        getTableData() {
            let params = {
                page: this.current_page,
                perPage: this.per_page,
                status: 3,
                type: [1, 2]
            }
            if (this.activeTabs != 'reward') {
                params = {
                   page: this.current_page,
                    perPage: this.per_page,
                    type: [1, 2],
                    audit_status: 3
                }
            }
            params = {...params, ...this.sort_params, ...this.search_params}
            if (this.search_params.type) {
                delete params.type
                params.type = [this.search_params.type]
            }
            let url = this.activeTabs == 'reward' ? '/api/rewardRecord' : '/api/deduction'
            this.loading = true
            this.$axios.get(url, {
                params: params
            }).then(res => {
                if (res.data.code == 200) {
                    this.tableData = res.data.data
                    this.total = res.data.page.total
                    this.loading = false
                } else {
                    this.loading = false
                    this.$message({
                        type: 'error',
                        message: res.data.message
                    })
                }
            })
        },
        addFilterCondition(item) {
            let filterItem = {
                value: '',
                label: item.label,
                parameter: item.props,
                key: Date.now()
            }

            if (this.conditionForm.condition.length > 0) {
                let conditionlabels = []
                for (let i = 0; i < this.conditionForm.condition.length; i++) {
                    conditionlabels.push(this.conditionForm.condition[i].label)
                }
                let Check = conditionlabels.indexOf(item.label)
                Check == -1 ? this.conditionForm.condition.push(filterItem) : this.$message.error('请勿重复添加')
            } else {
                this.conditionForm.condition.push(filterItem)
            }

            this.showFilterCondition = false;
        },
        removeDomain(item) {
            let index = this.conditionForm.condition.indexOf(item)
            if (index !== -1) {
                this.conditionForm.condition.splice(index, 1)
            }
            if (item.label === '时间选择') {
                delete this.search_params.start_time
                delete this.search_params.end_time
            }
            let props = JSON.parse(JSON.stringify(this.conditionForm.condition))
            let params = {}
            props.forEach(v => {
                params[v.parameter] = v.value
            })
            if (params.time) {
                params.start_time = params.time[0]
                params.end_time = params.time[1]
                delete params.time
            }
            this.current_page = 1
            this.$refs['order-table'].clearSort()
            this.sort_params = {}
            this.search_params = {...params}
            this.getTableData()
        },
        submitsearch(formName) {
            let that = this
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let props = JSON.parse(JSON.stringify(this.conditionForm.condition))
                    let params = {}
                    props.forEach(v => {
                        params[v.parameter] = v.value
                    })
                    if (params.time) {
                        params.start_time = params.time[0]
                        params.end_time = params.time[1]
                        delete params.time
                    }
                    this.current_page = 1
                    this.$refs['order-table'].clearSort()
                    this.sort_params = {}
                    this.search_params = {...params}
                    this.getTableData()
                    this.showFilterCondition = false
                    this.showFilter = false
                }
            })
        },
        resetForm(formName) {
            this.$refs[formName].resetFields()
            this.conditionForm.condition.forEach(v => {
                if (v.value) {
                    v.value = null
                }
            });
            this.$refs['order-table'].clearSort()
            this.sort_params = {}
            this.search_params = {}
            this.$nextTick(() => {
                this.$refs[formName].clearValidate()
            })
            // this.getTableData()
            // this.showFilterCondition = false
            // this.showFilter = false
        },
        getAllAgent() {
            this.$axios.get('api/user/agent').then(res => {
                if (res.data.code == 200) {
                    this.agentOptions = res.data.data
                }
            }).catch(err => {
                this.$message({
                    type: "err",
                    message: err
                });
            });
            this.$axios.get('api/user/all_sub_admin').then(res => {
                if (res.data.code == 200) {
                    this.adminOptions = res.data.data
                    console.log(res.data)
                }
            }).catch(err => {
                this.$message({
                    type: "err",
                    message: err
                });
            });


        },
    },

    watch: {

    }
}
</script>

<style lang="less" scoped>
.order-sum {
    height: 100%;
    .tabs-wrap {
        .tabs {
            width: 100%;
        }
        .search-wrap {
            margin-top: -50px;
        }
    }
    /deep/.el-table {
		.img-wrap {
			display: flex;
            justify-content: center;
            > div {
                height: 23px;
            }
			.el-image {
                width: 23px;
				height: 23px;
			}
		}
	}
    /deep/.ivu-poptip-inner {
		min-width: 450px;
		// height: 300px;
		overflow-y: scroll;
	}

	/deep/.poptip-condition .ivu-poptip-inner {
		min-width: 180px;
	}

	.demo-dynamic {
		padding-left: 10px;

		.el-form-item {
			margin-bottom: 12px;
		}

		.el-input {
			width: 240px;
		}

		.el-date-editor {
			width: 240px;
		}

		.el-button {
			padding: 9px 15px;
			vertical-align: baseline;
		}

		.el-form-item__error {
			padding-top: 0;
		}
	}

	.poptip-condition {
		display: block;
		margin-top: 10px;

		.poptip-condition-item {
			line-height: 25px;
			cursor: pointer;
		}

		.poptip-condition-add {
			font-size: 14px;
		}
	}

	.btns {
		margin-top: 10px;
    }
    .el-select {
        width: 240px;
    }
}
</style>
